import navToNext from '../../../wxjs/navToNext.js'
const app = getApp();

var data = {
  statusBarHeight: app.globalData.statusBarHeight,
  xhx_images: app.xhx_images,
  xhx_route: app.xhx_route,
  paySuccess:false,
  today:'',
  // status:0, //0:报名中；1：进行中；2：已结束;

  selfChallengeId:null,
  isLogin:false,
  selfDetail:{},
};

function navToNext1 (e) {
  var that = this
  navToNext.navToNext(e, that.data.selfDetail.matchScheduleInfo.startTime, that.data.selfDetail.matchScheduleInfo.endTime)
}

var currentPage = {
  data,
  onLoad,
  onShow,
  getDetail,
  getRunData,
  addUserKcal,
  getCurDay,
  navToNext1,

  onMyEvent,
  getFont,
  toUsers() {
    var that = this
    wx.navigateTo({
      url: app.xhx_route.joinUsers + '?id=' + that.data.selfChallengeId,
    })
  },
  onShareAppMessage: function () {
    const that = this;
    const selfChallengeId = that.data.selfChallengeId;
    return {
      title: '',
      path: `${app.xhx_route.selfChallengeDetail}?uuid=` + selfChallengeId
    }
  },
  onPullDownRefresh: function () {
    // wx.startPullDownRefresh();
    this.getDetail();
    wx.stopPullDownRefresh();
  },
  requestSubscribeMessage: function () {
    const that = this;
    wx.requestSubscribeMessage({
      tmplIds: ['PL7yUBWhTfLbqlML4DY314t-6ndp1vu6ZQsaP331FUA'],
      success(res) {
        console.log("success", res)
        const status = res['PL7yUBWhTfLbqlML4DY314t-6ndp1vu6ZQsaP331FUA'];
        if (status == 'accept') {
          app.middleware.requestAjax({
            serAddr: app.serAddrs.selfSetTemplateMsg,
            data: {
              matchId: that.data.selfChallengeId || '',//打卡赛id
              matchType: 2,//打卡赛类型：1官方 2自定义
            },
            complete: function (res) {
              app.showToast(res.msg, 3000);
            }
          })
        }
      },
      fail(res) {
        console.log("fail", res)
      }
    })
  },
};
var page = Object.assign({}, currentPage);

Page(page);

function onLoad(options) {

  // let userId;
  let selfChallengeId = options && options.uuid || options.id || "";

  // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
  var scene = options && options.q && decodeURIComponent(options.q) || '';
  // console.log("【league】options======>", options);
  // console.log("【league】scene======>", scene);
  // 普通二维码进入怎么也得有10个字符
  if (scene.length > 10) {
    // 是否为json格式校验
    var tempScenes = scene.split("params=");
    if (tempScenes.length > 1) {
      tempScenes = tempScenes[1];
      var firstChar = tempScenes.charAt(0);
      var lastChar = tempScenes.charAt(tempScenes.length - 1);
      if (firstChar == "{" && lastChar == "}") {
        tempScenes = JSON.parse(tempScenes);
        // userId = tempScenes.userId;
        selfChallengeId = tempScenes.uuid;
      }
    }
  }
  wx.showLoading({
    title: '加载中',
  });
  const that = this;
  that.setData({
    selfChallengeId
  })
  app.xlogin.getUser(function (res) {
    var myInfo = app.isNavigateToLogin();
    if (!myInfo) return;

    myInfo = app.isNavigateToBind();
    if (!myInfo) return;

    that.setData({
      selfChallengeId: selfChallengeId
    })
  })
  that.getCurDay();
  that.getFont();
}
function getCurDay(){
  var d = new Date()
  var y = d.getFullYear()
  var m = d.getMonth()+1;
  if (m < 10) {
    m = '0' + m
  }
  var d1 = d.getDate()
  if (d1 < 10) {
    d1 = '0' + d1
  }
  var date = [y, m, d1].join('-');
  this.setData({
    today: date
  })
}

function onShow() {
  const that = this;
  app.xlogin.getUser(function (res) {
    var myInfo = app.isNavigateToLogin();
    if (!myInfo) {
      that.setData({
        isLogin: false
      })
      return;
    }

    myInfo = app.isNavigateToBind();
    if (!myInfo) {
      that.setData({
        isLogin: false
      })
      return;
    }
    if (!that.data.isLogin) {
      that.getRunData();
      that.setData({
        isLogin: true
      })
    }
  })
}

function getDetail(){
  const that = this;
  var param={};
  param.id = that.data.selfChallengeId;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.selfGetDetail,
    data: param,
    cancelToast: true,
    success: function (res) {
      wx.hideLoading();
      var data=res.data;
      if(!data) return;

      var broadCastParam = {};
      broadCastParam.broadCastList = data.broadCastList;
      broadCastParam.scheduleStatus = data.matchScheduleInfo.scheduleStatus;
      data.broadCastList = broadCastParam;

      var customMatchFinance = data.customMatchFinance||{};
      customMatchFinance.realJoinPeopleNumber = data.matchScheduleInfo.realJoinPeopleNumber;
      customMatchFinance.price = data.matchScheduleInfo.price;
      data.customMatchFinance = customMatchFinance;

      var challengeRule={};
      challengeRule.limitNumber = data.customMatchRule.limitNumber + ' 人'
      challengeRule.matchWay = data.matchScheduleInfo.matchWay;
      challengeRule.dayAim = data.matchScheduleInfo.dayAim;
      challengeRule.price = data.matchScheduleInfo.price;
      challengeRule.startTime = data.matchScheduleInfo.startTime;
      challengeRule.endTime = data.matchScheduleInfo.endTime;
      challengeRule.customScheduleDays = data.matchScheduleInfo.customScheduleDays;
      challengeRule.rewardMold = data.matchScheduleInfo.rewardMold == 1 ? '平分奖金池' : data.matchScheduleInfo.rewardMold == 2 ? '抢红包模式' : data.matchScheduleInfo.rewardMold == 3 ? '每天分配一次奖金' : data.matchScheduleInfo.rewardMold == 4 ?'流水赛':'';

      // 最多展示五个头像，超过忽略
      if (data.joinedUser.joinedUserList.length > 5) {
        data.joinedUser.joinedUserListTopFive = [
          data.joinedUser.joinedUserList[0],
          data.joinedUser.joinedUserList[1],
          data.joinedUser.joinedUserList[2],
          data.joinedUser.joinedUserList[3],
          data.joinedUser.joinedUserList[4]
        ]
      } else {
        data.joinedUser.joinedUserListTopFive = [...data.joinedUser.joinedUserList]
      }
      
      that.setData({
        selfDetail: data,
        challengeRule: challengeRule
      })
    },
    fail: function (res) {
      app.middleware.showToast(res && res.msg || "加载失败");
    }
  })
}

// 获取微信步数
function getRunData() {
  const that = this;
  wx.login({
    success(res) {
      if (res.code) {
        var code = res.code;
        wx.getWeRunData({
          success(res) {
            var param = {};
            param.wxCode = code;
            param.type = 3;
            param.iv = res.iv;
            param.encryptedData = res.encryptedData;
            that.addUserKcal(param);
          },
          fail: function (res) {
            app.middleware.showToast('授权失败,无法同步微信步数！');
            that.getDetail();
          }
        })
      } else {
        app.middleware.showToast('登录失败,无法同步微信步数！');
        that.getDetail();
      }
    }
  })
}

function addUserKcal(param) {
  const that = this;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.addUserKcal,
    data: param,
    cancelToast: true,
    success: function (res) {
      that.getDetail();
      // console.log('=================', res)
    },
    fail: function (res) {
      app.middleware.showToast(res && res.msg || "加载失败");
      that.getDetail();
    }
  })
}


function getFont() {
  wx.loadFontFace({
    family: 'zihun35hao-jindianyahei',
    source: 'url("https://happyfit.oss-cn-shenzhen.aliyuncs.com/font.ttf")',
    success: function (res) {
      // console.log('======================', res.status)
    },
    fail: function (res) {
      // console.log('======================', res.status)
    },
    complete: function (res) {
      // console.log('======================', res.status);
    }
  });
}

function onMyEvent(e) {
  const that=this;
  var payBtn = e.detail.payBtn;
  // console.log('========================vvvvvvvvvvvvvvvvvvvvvvv', e.detail.payBtn)
  if (payBtn){
    that.setData({
      paySuccess:true
    });
    var timer1=null;
    clearTimeout(timer1);
    //设置一次性定时器
    timer1 = setTimeout(function () {
      that.getRunData();
      that.setData({
        paySuccess: false
      });
    }, 3000);
  }else{
    that.onShareAppMessage();
  }
  
}

